const http = require('http');
const url = require('url');
const { StringDecoder } = require('string_decoder');

const server = http.createServer((req, res) => {
    const parsedUrl = url.parse(req.url, true);
    const path = parsedUrl.pathname;
    const trimmedPath = path.replace(/^\/+|\/+$/g, '');
    const method = req.method.toLowerCase();

    const queryStringObject = parsedUrl.query;

    const headers = req.headers;

    const decoder = new StringDecoder('utf-8');
    let buffer = '';

    req.on('data', (data) => {
        buffer += decoder.write(data);
    });

    req.on('end', () => {
        buffer += decoder.end();

        const data = {
            trimmedPath,
            queryStringObject,
            method,
            headers,
            payload: buffer,
        };

        if (trimmedPath === 'web-api/model/imageAI' && method === 'post') {
            handleImageAIPost(data, (statusCode, payload) => {
                res.setHeader('Content-Type', 'application/json');
                res.writeHead(statusCode);
                res.end(JSON.stringify(payload));

                console.log(`Returning this response: ${statusCode} ${JSON.stringify(payload)}`);
            });
        } else {
            handlers.notFound(data, (statusCode, payload) => {
                res.setHeader('Content-Type', 'application/json');
                res.writeHead(statusCode);
                res.end(JSON.stringify(payload));

                console.log(`Returning this response: ${statusCode} ${JSON.stringify(payload)}`);
            });
        }
    });
});

const PORT = 18081;

server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

const handlers = {};

handlers.notFound = (data, callback) => {
    callback(404, { message: 'Not Found' });
};

function handleImageAIPost(data, callback) {
    const { payload } = data;
    try {
        const requestData = JSON.parse(payload);

        const { image1, image2, methodType, result } = requestData;

        if (!image1) {
            callback(400, { errors: '影像文件1(image1)参数不能为空' });
            return;
        }

        if (!methodType) {
            callback(400, { errors: '方法类型(methodType)参数不能为空' });
            return;
        } else {
            if (methodType < 1 || methodType > 4) {
                callback(400, { errors: '方法类型(methodType)参数应为1-4' });
                return;
            }

            if (methodType > 2 && !image2) {
                callback(400, { errors: '影像文件2(image2)参数不能为空' });
                return;
            }

            const filenameWithoutExtension = image1.replace(/\.[^.]+$/, '');

            callback(200, {
                message: '参数验证成功，返回结果如下：',
                params: { image1, image2, methodType },
                data: {
                    result: `${filenameWithoutExtension}_${methodType}.shp`,
                },
            });
        }
    } catch (error) {
        callback(400, { errors: 'Invalid JSON payload' });
    }
}
